<template>
    <div>
        <div :style="{padding: '24px', minHeight: '480px', background: '#fff'}">
            <el-form ref="storageBill" label-width="80px" :model="storageBill" :rules="rules">
                <el-form-item label="发往仓库" prop="warehouseId">
                    <el-select size="small" @change="changeWare" v-model="storageBill.warehouseId" placeholder="发往仓库" style="width: 240px">
                        <el-option v-for="ware in warehouses" :key="ware.id" :label="ware.name" :value="ware.id">
                        </el-option>
                    </el-select>
                    <el-button style="margin-left: 10px" type="success" :loading="loadingWarehouse" @click="getWarehouse" size="small">获取仓库信息</el-button>
                </el-form-item>
                <el-form-item label="跟踪单号" prop="trackingNo">
                    <el-input size="small" v-model="storageBill.trackingNo" placeholder="跟踪单号,快递单号" style="width: 240px" />
                    <label>国内快递号</label>
                </el-form-item>
                <el-form-item label="箱唛抬头" prop="shippingNo">
                    <el-input size="small" v-model="storageBill.shippingNo" placeholder="箱唛抬头" style="width: 240px" />
                    <label>可自定义</label>
                </el-form-item>
                 <el-form-item label="柜号" prop="remark">
                    <el-input size="small" v-model="storageBill.remark" placeholder="备注" style="width: 240px" />
                </el-form-item>
                <el-form-item label="类型" prop="counter">
                    <el-radio-group v-model="storageBill.counter">
                        <el-radio :label="0">散货</el-radio>
                        <el-radio :label="1">整柜</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="柜号" prop="counterNo">
                    <el-input size="small" v-model="storageBill.counterNo" placeholder="柜号" style="width: 240px" />
                </el-form-item>
                <!--  <el-form-item>
                    <el-checkbox size="small" :true-label="1" :false-label="0" v-model="storageBill.confirmType">以到货为准,勾选此项将以收到的货品为准，不再另行通知</el-checkbox>
                </el-form-item> -->
            </el-form>
            <!--- 货品选择-->
            <el-divider>货品选择</el-divider>
            <el-form ref="el-form-item" label-width="80px" :inline="true" :model="item">
                <el-form-item prop="productId">
                    <el-select size="small" style="width: 280px" @change="changeProduct" clear="item={}" clearable :loading="searchLoading" placeholder="可输入、sku码 进行搜索" filterable remote :remote-method="remoteMethod" v-model="item.productId">
                        <el-option v-for="(product,ind) in products" :key="ind" :label="product.variationName+','+product.skuCode" :value="product.id">
                            <span style="float: right;color: #8492a6; font-size: 13px">{{product.variationName}}</span>
                            <span style="float: left;">skuCode:{{product.skuCode }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="quantity" :rules="[{required:true,message:'入库数量不能为空', trigger: 'blur'}]">
                    <el-input size="small" type="number" v-model="item.quantity" placeholder="商品数量>0" />
                </el-form-item>
                <el-form-item>
                    <el-button size="small" type="primary" @click="submitForm('el-form-item')">添加</el-button>
                    <el-button size="small" type="primary" @click="chaxiang">自动拆箱</el-button>
                    <el-upload :data="extData" :before-upload="beforeCallback" :on-progress="progressCallback" :on-success="successCallback" style="float: right;margin-left: 20px;" :show-file-list="false" :on-error="errorCallback" class="upload-demo" :action="uploadurl" ref="upload">
                        <el-button size="small" type="success">批量Excel导入</el-button>
                    </el-upload>
                </el-form-item>
            </el-form>
            <!--列表项-->
            <el-form :inline="true" ref="itemForm" :model="storageBill">
                <el-table :data="storageBill.items" stripe style="width: 100%">
                    <el-table-column prop="boxNo" label="箱号" width="120">
                        <template slot-scope="scope">
                            <el-form-item :rules="[{required:true,message:'箱号不能为空'}]" :prop="'items.' + scope.$index + '.boxNo'">
                                <el-input size="small" v-model="scope.row.boxNo"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column prop="productName" label="图片" width="120">
                        <template slot-scope="scope">
                            <el-image :src="scope.row.thumb" />
                        </template>
                    </el-table-column>
                    <el-table-column prop="productName" label="商品名称" width="180">
                    </el-table-column>
                    <el-table-column prop="variationName" label="商品规格" width="180">
                    </el-table-column>
                    <el-table-column prop="skuCode" label="sku编码" width="180">
                    </el-table-column>
                    <el-table-column prop="quantity" label="数量" width="120">
                        <template slot-scope="scope">
                            <el-form-item :rules="[{required:true,message:'数量不能为空'}]" :prop="'items.' + scope.$index + '.quantity'">
                                <el-input size="small" v-model="scope.row.quantity"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column prop="length" label="外箱长(cm)" width="120"> <template slot-scope="scope">
                            <el-form-item :rules="[{required:true,message:'长不能为空'}]" :prop="'items.' + scope.$index + '.length'">
                                <el-input size="small" v-model="scope.row.length"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column prop="width" label="外箱宽(cm)" width="120">
                        <template slot-scope="scope">
                            <el-form-item :rules="[{required:true,message:'宽不能为空'}]" :prop="'items.' + scope.$index + '.width'">
                                <el-input size="small" v-model="scope.row.width"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column prop="height" label="外箱高(cm)" width="120"> <template slot-scope="scope">
                            <el-form-item :rules="[{required:true,message:'高不能为空'}]" :prop="'items.' + scope.$index + '.height'">
                                <el-input size="small" v-model="scope.row.height"></el-input>
                            </el-form-item>
                        </template>
                    </el-table-column>
                    <el-table-column prop="volume" label="体积(m³)" width="120"> <template slot-scope="scope">
                            <!--     <el-form-item :rules="[{required:true,message:'体积自动计算'}]" :prop="'items.' + scope.$index + '.volume'">
                                <el-input size="small" v-model="scope.row.volume"></el-input>
                            </el-form-item> -->
                            {{(scope.row.width*scope.row.length*scope.row.height)/1000000 | toFixed(4)}}
                        </template>
                    </el-table-column>
                    <el-table-column prop="id" label="操作">
                        <template slot-scope="scope">
                            <el-form-item>
                                <el-button size="small" @click.prevent="removeDomain(scope.row)">删除</el-button>
                            </el-form-item>
                        </template>
                    </el-table-column>
                </el-table>
            </el-form>
            <div style="margin-top: 20px;text-align: center;">
                <el-button size="small" @click="cancel">取消</el-button>
                <el-button size="small" type="primary" :loading="modalLoading" @click="ok">确定提交</el-button>
            </div>
        </div>
        <CStorageBox @boxCallBack="boxCallBack" ref="refStorageBox"></CStorageBox>
    </div>
</template>
<script>
import CStorageBox from "./CStorageBox.vue"
import api from "@/api/api"
import {doStorageBillCreate,getWmsList,searchStorageProductList} from "@/api/ProductApi"
export default {
    name: 'StorageBill',
    data() {
        return {
            extData: {
                sessionKey: localStorage.getItem('sessionKey'),
                token: localStorage.getItem('token')
            },
            uploadurl: api.uploadPurchaseUrl,
            searchLoading: false,
            loadingWarehouse: false,
            modalLoading: false,
            others: {

            },
            products: [],

            item: {
                productName: null, //货号
                productId: null, //實際id
                skuCode: null, //sku码
                quantity: null
            },
            storageBill: {
                warehouseId: 0,
                items: [],
                shippingNo: "",
                counter: 0
            },
            warehouses: [],
            rules: {

            },

            storageBillId: null
        };
    },
    mounted: function() {

        this.getWarehouse();
    },
    components: { CStorageBox },
    methods: {
        errorCallback: function(file) {
            this.hideLoading();
            this.errorMessage("上传失败！");
        },
        beforeCallback: function() {
            if (!this.storageBill.warehouseId) {
                this.errorMessage("请先选择仓库！");
                return;
            }
            this.extData['warehouseId'] = this.storageBill.warehouseId;
            this.showLoading();
        },
        progressCallback: function() {

        },
        successCallback: function(body, file, fileList) {
            var me = this;
            me.hideLoading();

            if (body.status == 0) {
                body.obj.forEach((titem, ind) => {
                    let it = {
                        productName: titem.productName,
                        variationName: titem.variationName,
                        skuCode: titem.skuCode,
                        productId: titem.id,
                        quantity: titem.quantity,
                        thumb: titem.pics,
                        boxNo: this.getBoxCount() + 1,
                        width: titem.width,
                        height: titem.height,
                        length: titem.length
                    };
                    this.storageBill.items.push(it);
                });
            } else {
                this.errorMessage(body.info);
            }
        },

        changeWare: function(warehouseId) {
            this.warehouses.forEach((ware, ind) => {
                if (ware.warehouseId == warehouseId) {
                    this.storageBill.shippingNo = ware.shippingNo;
                }
            });
            this.products = [];
            this.storageBill.items = [];
        },
        getBoxCount() {
            var dt = [];
            for (var i = 0; i < this.storageBill.items.length; i++) {

                let bx = parseInt(this.storageBill.items[i].boxNo);
                if (dt.indexOf(bx) < 0) {
                    dt.push(bx);
                }
            }
            return dt.length;
        },
        chaxiang() {
            var me = this;
            if (!me.item.productId) {
                me.errorMessage("请先选择商品");
                return false;
            }
            if (!me.item.quantity) {
                me.errorMessage("请输入商品数量");
                return false;
            }
            this.$refs['refStorageBox'].showDialog();

        },
        boxCallBack(count, length, width, height) {
            var it = Math.ceil(this.item.quantity / count);
            for (var i = 0; i < it; i++) {
                let it2 = {
                    productName: this.item.productName,
                    variationName: this.item.variationName,
                    skuCode: this.item.skuCode,
                    productId: this.item.productId,
                    quantity: count,
                    thumb: this.item.thumb,
                    boxNo: this.getBoxCount() + 1,
                    width: width,
                    height: height,
                    length: length
                };
                //判断是否重复的Id
                this.storageBill.items.push(it2);

            }
            this.item = {
                productName: null, //名称
                variationName: null, //货号
                productId: null, //實際id
                skuCode: null, //sku码
                quantity: null,
                boxNo: null
            };
            this.$refs['refStorageBox'].hideDialog();

        },
        changeProduct: function(pr) {
            //商品选择
            var me = this;
            me.products.forEach((dt, ind) => {

                if (pr == dt.id) {
                    me.item.skuCode = dt.skuCode;
                    me.item.productName = dt.productName;
                    me.item.variationName = dt.variationName;
                    me.item.thumb = dt.pics;
                }
            });
        },
        removeDomain: function(it) {
            var index = this.storageBill.items.indexOf(it)
            if (index !== -1) {
                this.storageBill.items.splice(index, 1)
            }
        },

        submitForm(formName) {
            var me = this;
            if (!me.item.productId) {
                me.errorMessage("请先选择商品");
                return false;
            }
            if (!me.item.quantity) {
                me.errorMessage("请输入商品数量");
                return false;
            }
            let it = {
                productName: me.item.productName,
                skuCode: me.item.skuCode,
                variationName: me.item.variationName,
                productId: me.item.productId,
                thumb: me.item.thumb,
                quantity: me.item.quantity,
                boxNo: me.getBoxCount() + 1
            };
            //判断是否重复的Id
            this.storageBill.items.push(it);
            this.item = {
                productName: null, //货号
                productId: null, //實際id
                skuCode: null, //sku码
                quantity: null,
                thumb: null,
                boxNo: 0
            };

        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        remoteMethod(query) {
            
            if (query != '') {
                this.loading = true;
            }
            var me = this;
            me.searchLoading = true;
            searchStorageProductList({ warehouseId: this.storageBill.warehouseId, type: 1, name: query }).then(response => {
                var body = response;
                if (body.status == 0) {
                    me.products = body.obj;
                }
                me.searchLoading = false;

            }, response => {
                me.searchLoading = false;
            });

        },

        getWarehouse: function() {

            var me = this;
            me.loadingWarehouse = true;
           getWmsList().then(response => {
                var body = response;
                if (body.status == 0) {

                    me.warehouses = body.obj;
                    if (body.obj.length > 0) {
                        // me.warehouse = body.obj[0];
                        me.storageBill.warehouseId = body.obj[0].id;
                        me.storageBill.shippingNo = body.obj[0].shippingNo;
                    }
                }
                me.loadingWarehouse = false;

            }, response => {
                me.loadingWarehouse = false;
            });
        },
        okSubmit() {
            var me = this;
            debugger;
            if (!me.storageBill.warehouseId) {
                me.errorMessage("请先选择要入库的商品");
                return false;
            }
            if (me.storageBill.items.length <= 0) {
                me.errorMessage("入库货品项目不能为空");
                return false;
            }
            me.modalLoading = true;
            let data = JSON.stringify(me.storageBill);
            doStorageBillCreate({ data: data,warehouseId:me.storageBill.warehouseId }).then(response => {
                var body = response;
                if (body.status == 0) {
                    me.successMessage("提交成功！");
                    me.modalEdit = false;
                    me.$router.push({ name: "StorageBillList" });



                } else {
                    me.errorMessage(body.info);
                }
                me.modalLoading = false;
            }, response => {
                me.modalLoading = false;
            });
        },
        ok: function() {

            this.$refs['storageBill'].validate((valid) => {

                if (valid) {

                    this.$refs['itemForm'].validate((svalid) => {
                        if (svalid) {
                            this.okSubmit();
                        } else {
                            this.errorMessage('请认真填写数据');
                        }
                    });

                } else {
                    this.errorMessage('请认真填写数据');
                }
            })


        },
        cancel: function() {
            this.$router.push({ name: "StorageBillList" })
        }
    }
}
</script>
<style scoped>
</style>